package consul_demo

import (
	"context"
	"protobuf/handler"
	"protobuf/pb"

	"github.com/asim/go-micro/plugins/registry/consul/v4"
	"go-micro.dev/v4"
	"go-micro.dev/v4/logger"
	"go-micro.dev/v4/registry"
)

// go-micro v4 提供plugins，只需要引入并创建实例之后，使用micro.Registry注册即可
func RegConsul() error {
	// register consul
	reg := consul.NewRegistry(func(options *registry.Options) {
		options.Addrs = []string{"172.19.129.62:8500"}
	})
	// create service
	srv := micro.NewService(
		micro.Name("future"),
		micro.Version("latest"),
		micro.Address(":9876"), // 指定端口
		// 注册consul中心
		micro.Registry(reg), // 注册到 consul 不能再用  micro call future Future.GetMinBar '{"instrument": "rb2205"}' 调用了!!!
	)

	// register handler
	if err := pb.RegisterFutureHandler(srv.Server(), &handler.Future{}); err != nil {
		logger.Fatal(err)
	}

	// run service
	err := srv.Run()
	return err
}

func RunConsul() error {
	reg := consul.NewRegistry(func(options *registry.Options) {
		options.Addrs = []string{"172.19.129.62:8500"}
	})

	service := micro.NewService(
		micro.Name("future_client"),
		micro.Registry(reg),
	)
	service.Init()

	client := pb.NewFutureService("future", service.Client())
	rsp, _ := client.GetMinBar(context.Background(), &pb.BarRequest{Instrument: "rb2211"})
	logger.Info(rsp.Instrument)

	// http 方式调用
	// services, err := reg.GetService("future")
	// if err != nil {
	// 	return errors.Wrap(err, "取服务 future")
	// }
	// if len(services) > 0 {
	// 	next := selector.RoundRobin(services)
	// 	node, err := next()
	// 	if err != nil {
	// 		return err
	// 	}
	// 	logger.Info(node.Id, "\n", node.Metadata)
	// }
	return nil
}
